package edu.whut.mall.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import edu.whut.mall.user.service.ITradeService;
import edu.whut.mall.common.mybatis.ParamsMap;
import edu.whut.mall.common.webException.HeheException;
import edu.whut.mall.common.enums.Sfstatus;
import edu.whut.mall.pojo.mapper.OrderMapper;
import edu.whut.mall.pojo.mapper.ProductSellMapper;
import edu.whut.mall.pojo.mapper.TradeMapper;
import edu.whut.mall.pojo.model.Order;
import edu.whut.mall.pojo.model.Trade;
import edu.whut.mall.common.vo.ProductSellVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import java.util.Date;
import java.util.List;



@Service
@Slf4j
public class TradeServiceImpl implements ITradeService {



    @Resource
    private TradeMapper tradeMapper;

    @Resource
    private ProductSellMapper productSellMapper;

    @Resource
    private OrderMapper orderMapper;

    /**
     * 支付
     * 1维护原来的去库存策略
     * 2 新增所有收益入账到钱包当中
     *
     * @Author shuxibing
     * @UpdateDate 2020/3/27 20:26
     * @Uint d9lab
     * @Description: 新接口，利润全部进入钱包表中
     */
    @Override
    public Trade pay(int tradeId){
        log.info("---------pay方法-----------");
        LambdaQueryWrapper<Order> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Order::getTradeId, tradeId);
        List<Order> orders = orderMapper.selectList(queryWrapper);
        Trade trade = tradeMapper.selectById(tradeId);
//        UserRole userRole = userRoleService.getOneUserRole(trade.getUser());
        log.info("orders:{}",orders);
        /**这一步调用新写的函数**/
        for (Order order : orders) {
            ProductSellVo productSell = productSellMapper.getProductSellById(order.getProductId());
            int productNumRest = productSell.getNumRest();
            if (order.getStatus() == Sfstatus.待付款) {
                if (order.getQuantity() <= productNumRest) {
                    ParamsMap map = ParamsMap.getPageInstance();
                    map.put("productId", order.getProductId());
                    map.put("quality", order.getQuantity());
                    map.put("updateTime", new Date());
                    log.info("-----start支付订单-----");
                    // 出售完成更新库存
                    productSellMapper.updateProductSellNumRest(map);
                    //如果零售模式不null,操作分红
                }else {
                    throw new HeheException("库存不足,无法完成支付");
                }
            }
        }
        //修改trade标志位
        trade.setPayTime(new Date());
        tradeMapper.updateById(trade);
        //修改order的订单
        for (Order order : orders) {
            order.setStatus(Sfstatus.待发货);
            order.setUpdateTime(new Date());
            orderMapper.updateById(order);
        }
        return trade;
    }

}

